import React, { Component } from 'react'
import { Route, Switch, Redirect, NavLink, withRouter } from 'react-router-dom'
import KeepAlive from 'react-activation'
import loadable from '@loadable/component'
import RightTopHead from './components/RightTopHead'

import { Menu, Button, Icon } from 'antd'
import styles from './App.module.less'
import SubMenu from 'antd/lib/menu/SubMenu';
import { MenuItem } from 'rc-menu';

const Home = loadable(() => import('@/pages/Home'))
const ResourceManage = loadable(() => import('@/pages/ResourceManage'))
const AccountPowerManage = loadable(() => import('@/pages/AccountPowerManage'))
const UserNumberManage = loadable(() => import('@/pages/UserNumberManage'))
const CapacityManage = loadable(() => import('@/pages/CapacityManage'))
const SystemManage = loadable(() => import('@/pages/SystemManage'))
const ChapterManage = loadable(() => import('@/pages/ChapterManage'))
const ResourcePowerManage = loadable(() => import('@/pages/ResourcePowerManage'))
const OnlineUserManage = loadable(() => import('@/pages/OnlineUserManage'))


//国粒logo
const logoBig = require('./components/img/logobig.png')
const logoSmall = require('./components/img/logosmall.ico')


/**
 * @waring icon与path都不得重复
 */
const routes = [
  { title: 'Home', path: '/home', component: Home, exact: true, icon: 'home' },
  {
    title: 'ResourceManage', component: '', exact: true, icon: 'book', children: [
      { title: 'Res-children01', path: '/resource-manage', component: ResourceManage, exact: true }
    ]
  },
  {
    title: 'AccountPowerManage', component: '', exact: true, icon: 'folder-open', children: [
      { title: 'account-children01', path: '/accountpower-manage', component: AccountPowerManage, exact: true }
    ]
  },
  // { title: 'AccountPowerManage', path: '/accountpower-manage', component: AccountPowerManage, exact: true, icon: 'folder-open' },
  { title: 'UserNumberManage', path: '/usernumber-manage', component: UserNumberManage, exact: true, icon: 'contacts' },
  { title: 'CapacityManage', path: '/capacity-manage', component: CapacityManage, exact: true, icon: 'cloud' },
  { title: 'SystemManage', path: '/system-manage', component: SystemManage, exact: true, icon: 'cluster' },
  { title: 'ChapterManage', path: '/chapter-manage', component: ChapterManage, exact: true, icon: 'profile' },
  { title: 'ResourcePowerManage', path: '/resourcepower-manage', component: ResourcePowerManage, exact: true, icon: 'appstore' },
  { title: 'OnlineUserManage', path: '/onlineuser-manage', component: OnlineUserManage, exact: true, icon: 'solution' },

]

class App extends Component {
  state = {
    collapsed: false,
    clientHeight: '100',
  }
  componentDidMount() {
    window.addEventListener('resize', this.resize)
    this.resize()
  }
  resize = () => {
    this.setState({ clientHeight: document.documentElement.clientHeight })
  }
  componentWillMount() {
    window.removeEventListener('resize', this.resize)
  }

  /**
   * @param {function} 导航栏伸缩
   */
  toggleCollapsed = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    })
  }
  render() {
    const { collapsed, clientHeight } = this.state
    return (
      <>
        <Menus menuRoute={routes} menucoll={collapsed} />
        <div className={styles.bigContainer} style={{ marginLeft: collapsed ? '80px' : '216px' }}>
          <div className={styles.topHead}>
            <span className={styles.togButton} onClick={this.toggleCollapsed}>
              <Icon type={collapsed ? 'menu-unfold' : 'menu-fold'} style={{ fontSize: '20px' }} />
            </span>
            <RightTopHead />
          </div>
          <div className={styles.content} style={{ height: Number(clientHeight) - 63 - 20 }}>

            <Switch>
              {routes.map(route => (
                route.path ? (<RouteGuide key={route.icon} {...route} />) : (
                  route.children.map(item => (
                    <RouteGuide key={item.path} {...item} />
                  ))
                )
              ))
              }

              <Redirect to="/" />
            </Switch>
          </div>
        </div>
      </>
    )
  }
}

/**
 * @description 路由守卫,用于处理鉴权和缓存
 * @param {ReactNode} component 内容组件
 * @param {String} [title] 路由的名称
 * @param {Boolean} [auth] 是否需要登录
 * @param {Boolean} [cache] 是否需要缓存路由
 * @param {any} [rest] 其他继承于'Route'组件的属性
 */
function RouteGuide({ component: Wrapper, title = '', auth = false, cache = false, ...rest }) {
  const isLogin = Boolean(window.localStorage.getItem('token'))
  // const shouldRender = auth ? isLogin : true
  const shouldRender = true

  return (
    <KeepAlive when={cache}>
      <Route {...rest} render={props => (shouldRender ? <Wrapper {...props} /> : <span>未登录</span>)} />
    </KeepAlive>
  )
}

/**
 * @description Menu 导航组件
 */
@withRouter
class Menus extends Component {
  state = {
    openKey: []
  }
  menu = (item) => {
    return (
      <Menu.Item key={item.path}>
        <NavLink to={item.path}>
          <Icon type={item.icon} style={{ fontSize: '16px' }} />
          <span>{item.title}</span>
        </NavLink>
      </Menu.Item>
    )
  }
  subMenu = (item) => {
    return (
      <SubMenu key={item.icon} title={<span><Icon type={item.icon} style={{ fontSize: '16px' }} /><span>{item.title}</span></span>}>
        {
          item.children.map(child => (
            <MenuItem key={child.path}>
              <NavLink to={child.path}>
                <span>{child.title}</span>
              </NavLink>
            </MenuItem>
          ))
        }

      </SubMenu>
    )
  }
  /**
   * @param {function} 控制只展开当前父节点
   * @param {arry} openKeys
   */
  onOpenChange = (openkeys) => {
    console.log('opkeys---', openkeys)
    // const latestOpenKey = openKeys.find(key => this.state.openKey.indexOf(key) === -1);
    const latestOpenKey = ''
    // if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
    //   this.setState({ openKey: openkeys });
    // } else {
    //   this.setState({
    //     openKey: latestOpenKey ? [latestOpenKey] : [],
    //   });
    // }
  }
  render() {
    const urlRoute = this.props.location.pathname
    const { menuRoute, menucoll } = this.props
    console.log('this.props.location', this.props.location)
    return (
      <div className={styles.menuCountainer} style={{ width: menucoll ? '80px' : '216px' }}>
        {
          menucoll ? (<img src={logoSmall} alt="国粒" className={styles.logoSmall} />) : (<img src={logoBig} alt="国粒" className={styles.logoBig} />)
        }

        <Menu
          defaultSelectedKeys={[urlRoute ? urlRoute : menuRoute[0].path || '']}
          mode="inline"
          theme="dark"
          inlineCollapsed={menucoll}
          // openKeys={this.state.openKey}
          onOpenChange={this.onOpenChange}
        >
          {menuRoute.map((item, index) => (
            item.path ? (this.menu(item)) : (this.subMenu(item))
          ))}
        </Menu>
      </div>
    )
  }
}

export default App
